<template>
  <div>
    <!-- 头部面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 进度条 -->
      <el-steps
        :space="200"
        :active="activeindex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form
        :model="addgoods"
        :rules="addgoodsrules"
        ref="addgoods"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeindex"
          :before-leave="beforleave"
          @tab-click="tabclick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addgoods.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addgoods.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addgoods.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addgoods.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addgoods.goods_cat"
                :options="catelist"
                :props="cateprops"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manytagdata"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  v-for="(i, index) in item.attr_vals"
                  :label="i"
                  :key="index"
                  >{{ i }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlytagdata"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action图片上传的后台地址 -->
            <el-upload
              :action="uploadurl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headobj"
              :on-success="fileup"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件,且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addgoods.goods_introduce"></quill-editor>
            <el-button type="primary" class="bttn" @click="addgood"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 显示图片 -->
    <el-dialog title="图片" :visible.sync="tpisblock" width="50%">
      <img :src="uploadptppath" class="tpblock" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      //进度条的进度
      activeindex: "0",
      //添加商品的数据
      addgoods: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        //图片的数组
        pics: [],
        //商品详情描述
        goods_introduce: "",
        attrs: [],
      },
      //添加商品的验证规则
      addgoodsrules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
      // 级联选择框数据
      catelist: [],
      // 级联选择框的配置对象
      cateprops: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
        checkStrictly: true,
      },
      //切换tab页签时表单数据是否验证通过
      istrue: true,
      // tag标签数据
      manytagdata: [],
      onlytagdata: [],
      uploadurl: "http://127.0.0.1:8888/api/private/v1/upload",
      //图片上传组件发送请求的请求头
      headobj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      uploadptppath: "",
      tpisblock: false,
    };
  },
  created() {
    this.getgoodscate();
  },
  methods: {
    //获取商品分类列表
    async getgoodscate() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200)
        return this.$message.error("获取分类列表失败");
      this.$message.success("获取分类列表成功");
      this.catelist = res.data;
    },
    //级联选择器发生改变的事件
    handleChange(keys) {
      if (keys.length < 3) {
        this.addgoods.goods_cat = [];
        return this.$message.error("亲选择三级分类");
      }
      this.tabclick()
      this.addgoods.goods_cat = keys;
    },
    //tab标签页切换事件
    beforleave(_, before) {
      if (before === "0") {
        this.$refs.addgoods.validate(async (valid) => {
          this.istrue = valid;
        });
      }
      if (!this.istrue) this.$message.error("检查表单数据是否填写完毕");
      return this.istrue;
    },
    async tabclick() {
      //当选择的是商品参数时执行
        const { data: res1 } = await this.$http.get(
          `categories/${this.catid}/attributes`,
          { params: { sel: "many" } }
        );
        if (res1.meta.status !== 200) return this.$message.error("获取数据失败");
        res1.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
        });
        // this.manytagdata = res.data;
        this.manytagdata = JSON.parse(JSON.stringify(res1.data));
      //选择的时商品属性时执行
        const { data: res2 } = await this.$http.get(
          `categories/${this.catid}/attributes`,
          { params: { sel: "only" } }
        );
        if (res2.meta.status !== 200) return this.$message.error("获取数据失败");
        this.onlytagdata = res2.data;
        this.$message.success("获取数据成功");

    },
    //处理图片预览
    handlePreview(file) {
      this.tpisblock = true;
      this.uploadptppath = file.response.data.url;
    },
    //移除图片
    handleRemove(file) {
      //获取删除图片的路径
      const filepath = file.response.data.tmp_path;
      //根据图片路径找到索引值
      const i = this.addgoods.pics.findIndex((x) => x.pic === filepath);
      this.addgoods.pics.splice(i, 1);
    },
    //图片上传成功
    fileup(res) {
      if (res.meta.status !== 200) return this.$message.error("上传失败");
      const picinfo = {
        pic: res.data.tmp_path,
      };
      this.addgoods.pics.push(picinfo);
    },
    //处理动态参数
    setmantdata(){
      //处理动态参数
      console.log(this.manytagdata);
      console.log(this.onlytagdata);
      
      this.manytagdata.forEach(item =>{
        const nitem ={
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(","),
        }
        this.addgoods.attrs.push(nitem)
      })  
      // 静态属性
      this.onlytagdata.forEach((item) => {
        const netitem = {
          attr_id: item.attr_id,
          attr_vals: item.attr_vals,
        };
        this.addgoods.attrs.push(netitem);
      })
    },
    //添加商品按钮
  async  addgood() {
      //先将商品信息进行深拷贝
      //提交给服务器的数据是深拷贝后的数据不是原始数据
      const naddgood = _.cloneDeep(this.addgoods);
      naddgood.goods_cat = naddgood.goods_cat.join(",");
      this.setmantdata()
      naddgood.attrs=this.addgoods.attrs
      //将商品信息发送到服务器
     const {data:res} = await this.$http.post('goods',naddgood)
     if(res.meta.status!=201) return this.$message.error('添加失败')
     this.$message.success('添加商品成功')
      this.$router.push('/goods')
    },
  },
  computed: {
    catid() {
      if (this.addgoods.goods_cat.length === 3)
        return this.addgoods.goods_cat[2];
      return "";
    },
  },
};
</script>

<style scoped>
.el-card {
  margin: 20px 0;
}
.el-steps {
  margin: 15px auto;
}
.tpblock {
  width: 100%;
}
.bttn {
  margin: 10px;
}
</style>

